 package srdb.migration.dbhandler.sybase;
 
   
 import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Set;

import srdb.migration.MigrationToolkit;
import srdb.migration.Utility;
import srdb.migration.common.IMTKConnection;
import srdb.migration.common.MTKConstants;
import srdb.migration.common.MTKMetaData;
import srdb.migration.schema.metadata.Column;
import srdb.migration.schema.metadata.Constraint;
import srdb.migration.schema.metadata.ConstraintList;
import srdb.migration.schema.metadata.Index;
import srdb.migration.schema.metadata.Table;
import srdb.migration.schema.metadata.View;
 
 public class MetaData extends MTKMetaData
 {
   private IMTKConnection conn = null;
   private DatabaseMetaData metaData = null;
   private String commaSepViewNames = null;
   private String commaSepTableNames = null;
 
   public MetaData(IMTKConnection conn)
     throws Exception
   {
     this.conn = conn;
     this.dbConn = conn.getConnection();
     this.metaData = this.dbConn.getMetaData();
   }
 
   public MetaData(IMTKConnection conn, String targetSchemaName)
     throws Exception
   {
     this.conn = conn;
     this.dbConn = conn.getConnection();
     this.metaData = this.dbConn.getMetaData();
     this.targetSchemaName = targetSchemaName;
   }
 
   public boolean supportsSynonyms()
   {
     return false;
   }
 
   protected void initSynonymStatement(String commaSepSynNames)
     throws SQLException
   {
   }
 
   protected void initTableStatement(String commaSepTableNames)
     throws SQLException
   {
     this.commaSepTableNames = removeSingleQuotes(commaSepTableNames);
   }
 
   public void getTables(String commaSepTableNames, boolean importViewAsTable)
     throws SQLException
   {
     super.getTables(removeSingleQuotes(commaSepTableNames), importViewAsTable);
 
     if (importViewAsTable) {
       initViewStatement(commaSepTableNames);
       getViewsAsTables();
     }
   }
 
   protected void initColumnStatement()
     throws SQLException
   {
   }
 
   protected Table getTable(String tableName)
     throws SQLException
   {
     PreparedStatement stmt = null;
     ResultSet rs = null;
     Table table = null;
     boolean colCaseSensitive = false;
     String colDefaultClause = null;
     Set<String> keySetColDefaultClause = null;
     HashMap mapColDefaultClause = null;
     try
     {
       if (MigrationToolkit.isFlagIgnoreCheckConstFilter())
       {
         String sqlColDefClause = "SELECT b.name column_name, a.text default_clause FROM syscomments a, syscolumns b WHERE a.id = b.cdefault AND b.id = object_id(?) AND cdefault > 0";
 
         stmt = this.conn.getConnection().prepareStatement(sqlColDefClause);
         stmt.setString(1, this.schema.getName() + "." + tableName);
         rs = stmt.executeQuery();
         mapColDefaultClause = new HashMap();
 
         while (rs.next()) {
           mapColDefaultClause.put(rs.getString(1), rs.getString(2));
         }
 
         rs.close();
         keySetColDefaultClause = mapColDefaultClause.keySet();
       }
 
       rs = this.metaData.getColumns(this.dbConn.getCatalog(), escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape()), escapeWildCharacters(tableName, this.metaData.getSearchStringEscape()), "%");
 
       while (rs.next()) {
         if (table == null) {
           table = new Table(this.schema, tableName, this.targetSchemaName);
         }
 
         String colName = rs.getString(4);
 
         Column column = new Column(table, colName);
 
         if (MigrationToolkit.isFlagIgnoreCheckConstFilter())
         {
           colDefaultClause = null;
 
           for (String key:keySetColDefaultClause)
           {
             if (key.equals(colName)) {
               colDefaultClause = (String)mapColDefaultClause.get(key);
               break;
             }
           }
 
         }
 
         table.addColumn(toEDBType(column, rs.getString(6), rs.getInt(7), rs.getInt(7), rs.getInt(9), rs.getString(11), isCaseSensitive(colName), colDefaultClause, rs.getString(12)));
       }
 
     }
     catch (SQLException se)
     {
       throw processException(se);
     } finally {
       if (rs != null) {
         rs.close();
       }
     }
 
     return table;
   }
 
   private void getViewsAsTables()
     throws SQLException
   {
     writeLog("Getting View Definitions");
     if ((this.commaSepViewNames != null) && (this.commaSepViewNames.trim().length() > 0))
     {
       String[] viewNames = this.commaSepViewNames.split(",");
       ResultSet rs = null;
       try {
         rs = this.metaData.getTables(this.dbConn.getCatalog(), escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape()), "%", new String[] { "VIEW" });
 
         if (rs != null) {
           Table table = null;
           while (rs.next())
             if (Arrays.binarySearch(viewNames, rs.getString(3)) >= 0) {
               table = getTable(rs.getString(3));
               if (table != null)
                 this.schema.addTable(table);
             }
         }
       }
       catch (SQLException exp)
       {
         throw processException(exp);
       } finally {
         if (rs != null)
           rs.close();
       }
     }
   }
 
   private Column toEDBType(Column column, String typeName, int length, int precision, int scale, String nullable, boolean caseSensitive, String defaultClause, String comments)
   {
     typeName = typeName.trim();
     if (typeName.equalsIgnoreCase("UNSIGNED SMALLINT")) {
       typeName = "INT";
     } else if (typeName.equalsIgnoreCase("UNSIGNED INT")) {
       typeName = "BIGINT";
     } else if (typeName.equalsIgnoreCase("UNSIGNED BIGINT")) {
       typeName = "NUMERIC";
       precision = 20;
       scale = 0;
     } else if ((typeName.equalsIgnoreCase("UNICHAR")) || (typeName.equalsIgnoreCase("nchar")))
     {
       typeName = "CHAR";
     } else if ((typeName.equalsIgnoreCase("TEXT")) || (typeName.equalsIgnoreCase("UNITEXT")))
     {
       typeName = "CLOB";
     } else if ((typeName.equalsIgnoreCase("UNIVARCHAR")) || (typeName.equalsIgnoreCase("NVARCHAR")))
     {
       typeName = "VARCHAR";
     } else if ((typeName.equalsIgnoreCase("BINARY")) || (typeName.equalsIgnoreCase("VBINARY")))
     {
       typeName = "BLOB";
     } else if (typeName.equalsIgnoreCase("IMAGE")) {
       typeName = "BYTEA";
     } else if (typeName.equalsIgnoreCase("MONEY")) {
       typeName = "NUMERIC";
     } else if (typeName.equalsIgnoreCase("smalldatetime")) {
       typeName = "TIMESTAMP";
     } else if (typeName.equalsIgnoreCase("SMALLMONEY")) {
       typeName = "NUMERIC";
     } else if (typeName.equalsIgnoreCase("DECIMAL")) {
       typeName = "NUMERIC";
     } else if (typeName.equalsIgnoreCase("NUMERIC IDENTITY")) {
       typeName = "NUMERIC";
     }
 
     column.addDetail(typeName.trim(), length, precision, scale, nullable, caseSensitive, defaultClause, comments, null);
 
     return column;
   }
 
   protected void initTriggerStatement(String commaSepTableNames)
     throws SQLException
   {
   }
 
   protected void initViewStatement(String commaSepViewNames)
     throws SQLException
   {
     this.commaSepViewNames = removeSingleQuotes(commaSepViewNames);
   }
 
   private View getView(String viewName)
     throws SQLException
   {
     View view = null;
     ResultSet rs = null;
     Statement stmt = null;
     String viewSource = "";
     String newSource = null;
     try {
       this.getViewsStr = ("SELECT text FROM syscomments WHERE id=object_id('" + this.schema.getName() + "." + viewName + "')");
 
       stmt = this.conn.getConnection().createStatement();
       rs = stmt.executeQuery(this.getViewsStr);
 
       if (rs != null) {
         view = new View(viewName, getSchema().getName());
         while (rs.next()) {
           viewSource = viewSource + rs.getString(1);
         }
 
         viewSource = viewSource.replace("\n--Adaptive Server has expanded all '*' elements in the following statement\n", " ");
 
         newSource = generateViewSource(viewSource);
         if (newSource == null)
         {
           viewSource = viewSource.substring(viewSource.toUpperCase().indexOf(" AS ") + 4);
         }
         else viewSource = newSource;
 
         Table viewTable = getTable(view.getName());
 
         view.setSQL(viewSource);
       }
     } catch (SQLException se) {
       throw processException(se);
     } finally {
       if (stmt != null) {
         stmt.close();
       }
       if (rs != null) {
         rs.close();
       }
     }
     return view;
   }
 
   protected void getViews()
     throws SQLException
   {
     writeLog("Getting View Definitions");
     View view = null;
 
     if ((this.commaSepViewNames != null) && (this.commaSepViewNames.trim().length() > 0)) {
       String[] viewNames = this.commaSepViewNames.split(",");
       for (String name : viewNames) {
         view = getView(name);
         if (view != null)
           this.schema.addView(view);
       }
     }
     else {
       ResultSet rs = null;
       try {
         rs = this.metaData.getTables(this.dbConn.getCatalog(), escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape()), "%", new String[] { "VIEW" });
 
         if (rs != null)
           while (rs.next())
           {
             if (!rs.getString(3).equalsIgnoreCase("sysquerymetrics")) {
               view = getView(rs.getString(3));
               if (view != null)
                 this.schema.addView(view);
             }
           }
       }
       catch (SQLException exp)
       {
         throw processException(exp);
       } finally {
         if (rs != null)
           rs.close();
       }
     }
   }
 
   protected void initSequenceStatement(String commaSepSequenceNames)
     throws SQLException
   {
   }
 
   protected void initProcStatement(String commaSepProcNames)
     throws SQLException
   {
   }
 
   protected void initPackageStatement(String commaSepPackageNames)
     throws SQLException
   {
   }
 
   protected void initConstraintStatement(String commaSepTableNames)
     throws SQLException
   {
     this.commaSepTableNames = removeSingleQuotes(commaSepTableNames);
   }
 
   protected void getConstraints()
     throws SQLException
   {
     writeLog("Getting Constraint Definitions");
     if ((this.commaSepTableNames != null) && (this.commaSepTableNames.length() > 0)) {
       String[] tableNames = this.commaSepTableNames.split(",");
       for (String name : tableNames)
         getTableConstraints(name);
     }
     else {
       ResultSet rs = null;
       try {
         rs = this.metaData.getTables(this.dbConn.getCatalog(), escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape()), "%", new String[] { "TABLE" });
 
         if (rs != null)
           while (rs.next())
             getTableConstraints(rs.getString(3));
       }
       catch (SQLException exp)
       {
         throw processException(exp);
       } finally {
         if (rs != null) {
           rs.close();
         }
 
       }
 
     }
 
     ConstraintList list = this.schema.getConstraints();
     if ((list != null) && (list.size() > 0)) {
       Constraint constraint = null;
       ArrayList cnames = new ArrayList();
       for (int i = 0; i < list.size(); i++) {
         constraint = list.get(i);
         if ((!constraint.getName().equalsIgnoreCase("PRIMARY")) && (!constraint.getName().equalsIgnoreCase("\"PRIMARY\"")) && (cnames.contains(constraint.getName())))
         {
           constraint.setName(null);
         }
         else cnames.add(constraint.getName());
       }
     }
   }
 
   private void getTableConstraints(String tableName)
     throws SQLException
   {
     Constraint constraint = null;
     Hashtable cache = new Hashtable();
     String colName = null;
     Column column = null;
     ResultSet rs = null;
     String schemaName = escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape());
     String pkConstraintName = "";
     try
     {
       String sql = "SELECT su.name table_schema, so.name table_name, si.name constr_name,  index_col('" + tableName + "', indid, 1) key1, index_col('" + tableName + "', indid, 2) key2, " + " index_col('" + tableName + "', indid, 3) key3, index_col('" + tableName + "', indid, 4) key4, " + " index_col('" + tableName + "', indid, 5) key5, index_col('" + tableName + "', indid, 6) key6 " + " FROM   sysindexes si, sysobjects so, sysusers su " + " WHERE si.id=so.id " + " AND user_name(so.uid)='" + schemaName + "' " + " AND so.uid*=su.uid " + " AND su.name = '" + schemaName + "' " + " AND object_name(si.id) = '" + tableName + "' " + " AND (status & 2048) = 2048 " + " AND si.indid > 0 " + " AND (si.status2 & 2 = 2) ";
 
       rs = this.conn.getConnection().createStatement().executeQuery(sql);
 
       if (rs != null)
       {
         String pkOriginalName = null;
         String pkName = null;
         while (rs.next())
         {
           pkOriginalName = rs.getString(3);
           pkName = pkOriginalName;
           if (!cache.containsKey(pkName)) {
             constraint = new Constraint(getTable(rs.getString(2)), pkName, isCaseSensitive(pkName));
 
             constraint.setType(MTKConstants.CONST_PRIMARY);
             cache.put(pkName, constraint);
             this.schema.addConstraint(constraint);
           } else {
             constraint = (Constraint)cache.get(pkName);
           }
 
           pkConstraintName = pkName;
 
           for (int i = 4; (i <= 9) && 
             (rs.getString(i) != null); i++)
           {
             colName = rs.getString(i);
             column = new Column(colName);
             column.setCaseSensitive(isCaseSensitive(colName));
             constraint.addColumn(column);
           }
         }
       }
     }
     catch (SQLException exp) {
       throw processException(exp);
     } finally {
       if (rs != null) {
         rs.close();
       }
     }
     cache.clear();
     try
     {
       rs = this.metaData.getImportedKeys(this.dbConn.getCatalog(), escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape()), tableName);
       ArrayList fkNames = getForeignKeyName(tableName);
       if (rs != null) {
         String keyName = null;
 
         while (rs.next())
         {
           if ((fkNames != null) && (fkNames.size() > 0) && 
             (rs.getRow() - 1 < fkNames.size())) {
             keyName = (String)fkNames.get(rs.getRow() - 1);
           }
 
           if (keyName == null)
           {
             keyName = rs.getString("FKTABLE_NAME") + "_fk" + rs.getShort("KEY_SEQ");
           }
 
           if (!cache.containsKey(keyName)) {
             constraint = new Constraint(getTable(rs.getString("FKTABLE_NAME")), keyName, isCaseSensitive(keyName));
 
             constraint.setType(MTKConstants.CONST_FOREIGN);
             constraint.setDeleteRule(MTKConstants.translateDeleteRule(rs.getShort("DELETE_RULE")));
 
             cache.put(keyName, constraint);
             this.schema.addConstraint(constraint);
           } else {
             constraint = (Constraint)cache.get(keyName);
           }
 
           colName = rs.getString("FKCOLUMN_NAME");
           column = new Column(colName);
           column.setCaseSensitive(isCaseSensitive(colName));
           constraint.addColumn(column);
 
           constraint.setRefIntegrityTable(rs.getString("PKTABLE_NAME"));
           colName = rs.getString("PKCOLUMN_NAME");
           column = new Column(colName);
           column.setCaseSensitive(isCaseSensitive(colName));
           constraint.addRefIntegrityColumn(column);
         }
       }
     } catch (SQLException exp) {
       throw processException(exp);
     } finally {
       if (rs != null) {
         rs.close();
       }
     }
     cache.clear();
 
     this.getConstraintsStr = "SELECT su.name as table_schema, object_name(sr.tableid) table_name, '' COLUMN_NAME, object_name(sr.constrid) CONSTRAINT_NAME, 'C' as ctype, '' key1, '' key2, '' key3, '' key4, '' key5, '' key6, m.text AS CONSTRAINT_CONDITION FROM sysconstraints sr, sysobjects so, sysusers su, syscomments m WHERE sr.constrid=so.id AND so.uid*=su.uid AND so.id*=m.id AND (so.sysstat & 15 = 7) AND  su.name = ? AND object_name(sr.tableid) = ?";
 
     PreparedStatement stmt = null;
     try
     {
       stmt = this.conn.getConnection().prepareStatement(this.getConstraintsStr);
       stmt.setString(1, schemaName);
       stmt.setString(2, tableName);
       rs = stmt.executeQuery();
 
       if (rs != null) {
         String keyName = null;
         String searchCondition = "";
         String tempOwnerName = this.schema.getName().toLowerCase() + ".";
         while (rs.next()) {
           keyName = rs.getString("CONSTRAINT_NAME").toLowerCase();
           if (!keyName.equalsIgnoreCase(pkConstraintName)) {
             colName = rs.getString("COLUMN_NAME").toLowerCase();
             searchCondition = rs.getString("CONSTRAINT_CONDITION");
             searchCondition = srdb.migration.dbhandler.sqlserver.MetaData.parseCheckConstraintClause(searchCondition);
             searchCondition = searchCondition.replaceAll(tempOwnerName, " ");
 
             if (!cache.containsKey(keyName)) {
               constraint = new Constraint(getTable(tableName), keyName, isCaseSensitive(keyName));
 
               constraint.setType(MTKConstants.CONST_CHECK);
               constraint.setSearchCondition(searchCondition);
               cache.put(keyName, constraint);
               this.schema.addConstraint(constraint);
             } else {
               constraint = (Constraint)cache.get(keyName);
             }
 
             if (isCaseSensitive(colName)) {
               colName = "\"" + colName + "\"";
             }
             constraint.addColumn(new Column(colName));
           }
         }
       }
     } catch (SQLException exp) {
       throw processException(exp);
     } finally {
       if (rs != null) {
         rs.close();
       }
 
       if (stmt != null) {
         stmt.close();
       }
     }
 
     cache.clear();
     cache = null;
   }
 
   protected void initIndexeStatement(String commaSepTableNames)
     throws SQLException
   {
     this.commaSepTableNames = removeSingleQuotes(commaSepTableNames);
   }
 
   protected void getIndexes()
     throws SQLException
   {
     writeLog("Getting Index Definitions");
     if ((this.commaSepTableNames != null) && (this.commaSepTableNames.trim().length() > 0))
     {
       String[] tableNames = this.commaSepTableNames.split(",");
       for (String name : tableNames)
         getTableIndexes(name);
     }
     else {
       ResultSet rs = null;
       try {
         rs = this.metaData.getTables(this.dbConn.getCatalog(), escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape()), "%", new String[] { "TABLE" });
 
         if (rs != null)
           while (rs.next())
             getTableIndexes(rs.getString(3));
       }
       catch (SQLException exp)
       {
         throw processException(exp);
       } finally {
         if (rs != null)
           rs.close();
       }
     }
   }
 
   private void getTableIndexes(String tableName)
     throws SQLException
   {
     Hashtable cache = new Hashtable();
     Index index = null;
     String colName = null;
     Column column = null;
     ResultSet rs = null;
     String schemaName = escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape());
 
     String sql = "select ind.name, bunique = (ind.status & 0x2),   index_col(tab.name, ind.indid, 1), index_col(tab.name, ind.indid, 2), index_col(tab.name, ind.indid, 3),  index_col(tab.name, ind.indid, 4), index_col(tab.name, ind.indid, 5), index_col(tab.name, ind.indid, 6),  index_col(tab.name, ind.indid, 7), index_col(tab.name, ind.indid, 8), index_col(tab.name, ind.indid, 9),  index_col(tab.name, ind.indid, 10), index_col(tab.name, ind.indid, 11), index_col(tab.name, ind.indid, 12),  index_col(tab.name, ind.indid, 13), index_col(tab.name, ind.indid, 14), index_col(tab.name, ind.indid, 15),  index_col(tab.name, ind.indid, 16)  from sysindexes ind, sysobjects tab  where ind.id = tab.id  and user_name(tab.uid)='" + schemaName + "'" + " and ind.indid > 0.0 and ind.indid < 255.0 " + " and tab.name = '" + tableName + "'";
 
     rs = this.conn.getConnection().createStatement().executeQuery(sql);
 
     ConstraintList listConstraints = this.schema.getConstraints();
     ArrayList constNamesList = new ArrayList();
     if ((listConstraints != null) && (listConstraints.size() > 0)) {
       for (int i = 0; i < listConstraints.size(); i++) {
         constNamesList.add(listConstraints.get(i).getName());
       }
     }
     try
     {
       if (rs != null) {
         String indexName = null;
         while (rs.next()) {
           indexName = rs.getString(1);
           if (!constNamesList.contains(indexName)) {
             if (!cache.containsKey(indexName)) {
               index = new Index(getTable(tableName), indexName);
               if (rs.getInt(2) == 2) {
                 index.setUnique(true);
               }
               cache.put(indexName, index);
               this.schema.addIndex(index);
             } else {
               index = (Index)cache.get(indexName);
             }
 
             for (int i = 3; (i <= 18) && 
               (rs.getString(i) != null); i++)
             {
               colName = rs.getString(i);
               column = new Column(colName);
               column.setCaseSensitive(isCaseSensitive(colName));
               index.addColumn(column);
             }
           }
         }
       }
     } catch (SQLException exp) {
       throw processException(exp);
     } finally {
       if (rs != null) {
         rs.close();
       }
     }
     cache.clear();
     cache = null;
   }
 
   protected void getTables()
     throws SQLException
   {
     writeLog("Getting Table Definitions");
 
     Table table = null;
 
     if ((this.commaSepTableNames != null) && (this.commaSepTableNames.trim().length() > 0)) {
       String[] tableNames = this.commaSepTableNames.split(",");
       for (String name : tableNames) {
         table = getTable(name);
         if (table != null)
           this.schema.addTable(table);
       }
     }
     else {
       ResultSet rs = null;
       try {
         rs = this.metaData.getTables(this.dbConn.getCatalog(), escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape()), "%", new String[] { "TABLE" });
 
         if (rs != null)
           while (rs.next()) {
             table = getTable(rs.getString(3));
             if (table != null)
               this.schema.addTable(table);
           }
       }
       catch (SQLException exp)
       {
         throw processException(exp);
       } finally {
         if (rs != null)
           rs.close();
       }
     }
   }
 
   protected void getProcedures()
     throws SQLException
   {
   }
 
   protected void getFunctions()
     throws SQLException
   {
   }
 
   protected void getPublicSynonyms()
     throws SQLException
   {
   }
 
   protected void getTriggers()
     throws SQLException
   {
   }
 
   protected void getSequences()
     throws SQLException
   {
   }
 
   protected void getPackages()
     throws SQLException
   {
   }
 
   public boolean isCaseSensitive(String identifierName)
   {
     return true;
   }
 
   protected void setConstraintColumnsPSParams(Constraint constraint)
     throws SQLException
   {
   }
 
   public String getVersion()
     throws SQLException
   {
     return "";
   }
 
   public String escapeWildCharacters(String objectName, String escapeString)
   {
     StringBuilder strBuilder = new StringBuilder();
 
     for (int i = 0; i < objectName.length(); i++) {
       char ch = objectName.charAt(i);
       if ((ch == '_') || (ch == '%'))
         strBuilder.append(escapeString + ch);
       else {
         strBuilder.append(ch);
       }
     }
     return strBuilder.toString();
   }
 
   private SQLException processException(SQLException exp)
   {
     return Utility.processException(exp);
   }
 
   private String generateViewSource(String viewSource)
   {
     String colAlias = null;
 
     String finalSource = "SELECT ";
     String finalTableNames = "";
     int clauseIndex = -1;
     boolean hasColumnAlias = false;
     String tableNames = "";
     String clause = null;
     try
     {
       int index = viewSource.toUpperCase().indexOf(" AS ");
 
       String ddlpart = viewSource.substring(0, index);
       String defpart = viewSource.substring(index + " AS ".length(), viewSource.length());
 
       if ((clauseIndex = defpart.toUpperCase().indexOf(" WHERE ")) > 0)
         clause = defpart.substring(clauseIndex, defpart.length());
       else if ((clauseIndex = defpart.toUpperCase().indexOf(" HAVING ")) > 0)
         clause = defpart.substring(clauseIndex, defpart.length());
       else if ((clauseIndex = defpart.toUpperCase().indexOf(" GROUP BY ")) > 0)
         clause = defpart.substring(clauseIndex, defpart.length());
       else if ((clauseIndex = defpart.toUpperCase().indexOf(" ORDER BY ")) > 0) {
         clause = defpart.substring(clauseIndex, defpart.length());
       }
 
       if ((ddlpart.indexOf("(") > 0) && (ddlpart.indexOf(")") > 0)) {
         colAlias = ddlpart.substring(ddlpart.indexOf("(") + 1, ddlpart.indexOf(")"));
         hasColumnAlias = true;
       }
 
       String colNames = defpart.substring(defpart.toUpperCase().indexOf("SELECT ") + "SELECT".length(), defpart.toUpperCase().indexOf(" FROM "));
 
       if (clauseIndex > 0)
         tableNames = defpart.substring(defpart.toUpperCase().indexOf(" FROM ") + " FROM ".length(), clauseIndex);
       else {
         tableNames = defpart.substring(defpart.toUpperCase().indexOf(" FROM ") + " FROM ".length(), defpart.length());
       }
 
       if ((tableNames != null) && (tableNames.indexOf(",") > 0)) {
         String[] listTableNames = tableNames.split(",");
         if ((listTableNames != null) && (listTableNames.length > 0)) {
           for (int i = 0; i < listTableNames.length; i++) {
             String temp = listTableNames[i];
 
             if (temp.indexOf(".") > 0) {
               String[] templist = tableNames.split("[.]");
               finalTableNames = finalTableNames + "\"" + templist[0].trim() + "\"" + "." + "\"" + templist[1].trim() + "\"";
             } else {
               finalTableNames = finalTableNames + "\"" + temp.trim() + "\"";
               if (i < listTableNames.length - 1)
                 finalTableNames = finalTableNames + ", ";
               else {
                 finalTableNames = finalTableNames + " ";
               }
             }
           }
         }
 
       }
       else if (tableNames.indexOf(".") > 0) {
         String[] templist = tableNames.split("[.]");
         finalTableNames = finalTableNames + "\"" + templist[0].trim() + "\"" + "." + "\"" + templist[1].trim() + "\"";
       } else {
         finalTableNames = finalTableNames + "\"" + tableNames.trim() + "\"" + " ";
       }
 
       if (colNames.indexOf(".") > 0) {
         String newColNames = "";
         if (colNames.indexOf(",") > 0) {
           String[] listColNames = colNames.split(",");
           for (int i = 0; i < listColNames.length; i++) {
             String[] listTemp = listColNames[i].split("[.]");
             newColNames = newColNames + "\"" + listTemp[0].trim() + "\"" + "." + "\"" + listTemp[1].trim() + "\"";
             if (i < listColNames.length - 1)
               newColNames = newColNames + ", ";
             else
               newColNames = newColNames + " ";
           }
         }
         else
         {
           String[] listTemp = colNames.split("[.]");
           newColNames = newColNames + "\"" + listTemp[0].trim() + "\"" + "." + "\"" + listTemp[1].trim() + "\"";
         }
         colNames = newColNames;
       }
 
       if (!hasColumnAlias) {
         if (clause == null)
           finalSource = finalSource + colNames + " FROM " + finalTableNames.trim();
         else {
           finalSource = finalSource + colNames + " FROM " + finalTableNames.trim() + " " + clause.trim();
         }
       }
       else
       {
         if (colNames.equals("")) {
           return null;
         }
 
         String[] listColNames = colNames.split(",");
         String[] listAliasNames = colAlias.split(",");
 
         if ((listAliasNames == null) || (listColNames == null) || (listColNames.length <= 0) || (listAliasNames.length <= 0)) {
           return null;
         }
 
         if (listAliasNames.length == listColNames.length) {
           for (int i = 0; i < listAliasNames.length; i++) {
             finalSource = finalSource + listColNames[i].trim() + " AS " + listAliasNames[i].trim();
             if (i < listAliasNames.length - 1) {
               finalSource = finalSource + " , ";
             }
           }
         }
         if (clause != null)
           finalSource = finalSource + " FROM " + finalTableNames.trim() + " " + clause.trim();
         else {
           finalSource = finalSource + " FROM " + finalTableNames.trim();
         }
       }
 
     }
     catch (Exception ex)
     {
       Utility.getLogger().error("Error in generateViewSource():", ex);
       return null;
     }
     return finalSource;
   }
 
   private ArrayList getForeignKeyName(String tableName) {
     ArrayList listName = new ArrayList();
     ResultSet rs = null;
     try {
       String schemaName = escapeWildCharacters(this.schema.getName(), this.metaData.getSearchStringEscape());
       String sql = "select object_name(sr.constrid) const_name  from sysreferences sr,  sysobjects so, sysusers su, sysobjects ftab, sysobjects rtab  where sr.tableid=so.id  and user_name(so.uid)='" + schemaName + "' " + " and so.uid*=su.uid " + " and sr.tableid = ftab.id and sr.reftabid = rtab.id " + " and su.name = '" + schemaName + "' " + " and object_name(sr.tableid) = '" + tableName + "' ";
 
       rs = this.conn.getConnection().createStatement().executeQuery(sql);
 
       if (rs != null)
         while (rs.next())
           listName.add(rs.getString(1));
     }
     catch (Exception ex)
     {
       ex.printStackTrace();
     } finally {
       try {
         if (rs != null)
           rs.close();
       }
       catch (SQLException sqle) {
       }
     }
     return listName;
   }
 
   public String[] getSchemas()
     throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void initDBLinkStatement() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getDBLinks() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getRoles() throws SQLException
   {
   }
 
   protected void getUsers() throws SQLException
   {
   }
 
   protected void initRoleStatement(String commaSepRoleNames) throws SQLException
   {
   }
 
   protected void initUserStatement(String commaSepUserNames) throws SQLException
   {
   }
 
   protected void initGrantStatement(String commaSepUserNames) throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getGrants() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   public int getDBServerMajorVersion() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   public int getDBServerMinorVersion() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void initRulesStatement(String commaSepRuleNames) throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getRules() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void initGroupsStatement(String commaSepGroupNames) throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getGroups() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   public String getDatabaseName()
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void initDomainsStatement(String commaSepDomainNames) throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getDomains() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void initCustomDataTypesStatement(String commaSepTypes) throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getCustomDataTypes() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void initAllPublicSynonymStatement() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void initAllPrivateSynonymStatement() throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getAllPublicSynonyms() throws SQLException {
     throw new UnsupportedOperationException("Not supported yet.");
   }
 
   protected void getAllPrivateSynonyms()
     throws SQLException
   {
     throw new UnsupportedOperationException("Not supported yet.");
   }

@Override
public void parseTables() throws SQLException {
	// TODO Auto-generated method stub
	
}

   @Override
   public String getParseTablesMsg() throws SQLException {
     return null;
   }
 }

/* 

 * 
 */